/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
  CCell, Cell, InputDatalist, InputIdProvider, InputLine, Table, TableBody, TableHead, TableRow, Text,
} from "customize-easy-ui-component";
import {InspectRecordLayout, InternalItemProps, RepLink, SelectInput, useItemInputControl} from "../../common/base";
import {tail注解} from "./orcBase";
import {usePrefixDataTable} from "../../hook/usePrefixData";
import {useOmnipotentPref, useOmnipotentPrefTitle} from "../../hook/useOmnipotentPref";
import {useMeasureInpFilter} from "../../common/hooks";
import {objNestSet} from "../../../common/tool";
import {renderBool有, render设备类别} from "../../common/render";


const lst减温方式=["喷淋式减温","表面式减温","混合式减温"];
const lst锅内处理=["锅内加药处理","部分软化处理","天然碱度法","其它处理"];
const lst软水设类=["钠离子交换器","膜处理(NF/RO)装置","阴、阳离子交换器","混合离子交换器","电除盐(EDI)装置"];
const lst原水=["自来水","地表水","地下水","凝结水"];
const lst取样装=["取样冷却器","取样点","无"];
const lst药剂类=["非磷酸盐型","磷酸盐型","与结垢物质作用后不生成固体不溶物的阻垢剂"];
const lst除氧设=["热力除氧","真空除氧","解析除氧","海绵铁","氧化还原树脂"];
export const configDevice = [
  [[{pr: '使用单位', span: 4, t: '名  称'}, '_$使用单位',],],
  [[{t: '地址'}, '_$使用单位地址'], ['邮政编码', '_$使用单位邮编']],
  [[{t: '安装地址'}, '_$设备使用地点'], ['联系人', '_$单位联系人']],
  //台账？：水质人员数量；
  [[{t: '联系电话'}, '_$使用单位电话'], ['持证水处理人员', {n: '持证水人', u: '人'}]],
  [[{pr: '分支机构', span: 2, t: '名  称'}, '_$分支机构',],],
  [[{t: '地址'}, '_$分支机构地址'],],
  [[{pr: '锅炉情况', span: 7, t: '锅炉类别'}, '_$设备类别', render设备类别], ['单位内编号', '_$单位内部编号']],
  [[{t: '锅炉型号'}, '_$型号'], ['锅炉出厂编号', '_$出厂编号']],
  [[{t: '使用登记证编号'}, '_$使用证号'], ['额定蒸发量', '_$额定蒸发量', 't/h']],
  [[{t: '设备代码'}, '_$设备代码'], ['额定压力', '_$额定压力', 'MPa']],
  //不用台账的：出水温度；
  [[{t: '锅炉循环方式'}, '_$水循环式'], ['出水温度', {n: '出水温', u: '℃'}]],
  //不用台账？ 回流温度 回水温==回油温度
  [[{t: '过热器'}, '_$有过热器', renderBool有('有过热器')], ['回水温度', {n: '回水温', u: '℃'}]],
  //= 过热蒸汽调温方式？
  [[{t: '过热器减温方式'}, {n: '减温式', t: 'l', l: lst减温方式}], ['蒸汽用途', '_$蒸汽用途']],
  //水处理方法"WATER_CLFF": "锅外水处理,锅内水处理",
  [[{pr: '水处理情况', span: 10, t: '水处理方法'}, '_$水处理式',], ['锅内处理方式', {n: '锅内处', t: 'l', l: lst锅内处理}]],
  [[{t: '软水设备类别'}, {n: '软水设', t: 'l', l: lst软水设类}], ['补给水类别', {n: '补水类', t: 'l', l: ["软化水", "除盐水"]}]],
  [[{t: '水处理设备型号'}, '_$水处设备型'], ['运行模式', '_$水处设运行']],
  [[{t: '设备制造单位'}, '_$水处设制单'], ['制水能力', '_$制水能力', 't/h']],
  [[{t: '采用原水'}, {n: '原水用', t: 'l', l: lst原水}], ['蒸汽冷凝水', {n: '蒸冷凝水', t: 'l', l: ["未回用", "回用"]}]],
  [[{t: '水汽取样装置'}, {n: '取样装', t: 'l', l: lst取样装}], [' ', {r: ' '}]],
  [[{t: '加药装置'}, {n: '加药', t: 'l', l: ["自动加药设备", "加药罐", "无"]}], ['水处理药剂类别', {n: '药类', t: 'l', l: lst药剂类}]],
  [[{t: '除氧方式'}, '_$除氧方式'], ['除氧剂类别', {n: '除氧剂类', t: 'l', l: ["亚硫酸盐", "非亚硫酸盐"]}]],
  [[{t: '除氧设备类别'}, {n: '除氧设', t: 'l', l: lst除氧设}], ['除氧器型号', '除氧型']],
  [[{t: '除氧器制造单位'}, '除氧制单'], ['除氧器出力', {n: '除氧力', u: 't/h'}]],
];


export const items处理系统 = [
  ['水员持证', [{t:'锅炉水处理管理状况', s:2},  ], '水处理作业人员持证情况*', ],
  ['制度执', [{}, ], '管理制度及执行情况*',  ],
  ['分析试剂', [{t:'水汽质量化验监控状况', s:3},  ], '化验仪器、分析试剂', ],
  ['测定项频', [{},  ], '测定项目和频次*',  ],
  ['水汽情况', [{},  ], '水汽质量合格情况*',  ],
    //低下 算右半边的：
  ['制水能', [{t:'水处理系统及运行状况',s:4},], '制水能力和出水质量*', ],
  ['加药操', [{},  ], '加药装置和加药操作',  ],
  ['水汽取样', [{},  ], '水汽取样装置',  ],
  ['除氧效', [{},  ], '除氧方式、除氧效果',  ],
  ['其它项频', [{t:'其它情况', s:1},  ], '蒸汽锅炉需监控的其它项目和频次', ],
];


//页眉不适合放入动态数据，对原版本的修改： 报告编号： 放入主体部分。兼容性；
const config概况1=configDevice.slice(0,6);
const config概况2=configDevice.slice(6);
export const 报告概况部分= ({ orc, rep,theme } : { orc: any, rep: any,theme:any}
) => {
    // const [renderUpper,renderMiddle]=useThreeColumnView({orc, config:config设备概况,slash:true,split:[6]});  ["4%", "14.1%", "38%", "9%", "5.1%","%"]
  const renderUpper=usePrefixDataTable({config: config概况1, orc, rep, slash:true});
  const renderMiddle=usePrefixDataTable({config: config概况2, orc, rep, slash:true});
  return <>
    <div css={{"@media print": {paddingBottom: '3.5rem', pageBreakInside: 'avoid'}}}>
      <Text id={'Conclusion'} variant="h2" css={{textAlign: 'center', marginTop: '1rem',
      }}>工业锅炉水处理定期检验报告</Text>
      <div css={{display: 'flex', justifyContent: 'space-between'}}>
        <Text></Text>
        <Text>报告编号：{rep.isp.no}</Text>
      </div>
    </div>
    <Table fixed={ ["5%", "14.1%", "56%", "9%", "5.1%","%"]  }
           css={{borderCollapse: 'collapse', "@media print": {marginTop: '-3.5rem'}}} tight miniw={800}>
      <TableBody>
        <RepLink rep={rep} tag={'Survey'}>
          {renderUpper}
        </RepLink>
      </TableBody>
    </Table>
    <Table fixed={ ["3%", "14.1%", "38%", "9%", "5.1%","%"]  }
            css={{borderCollapse: 'collapse', }} tight miniw={800}>
      <TableBody>
        <RepLink rep={rep} tag={'Survey'}>
          {renderMiddle}
        </RepLink>
        <TableRow >
          <CCell colSpan={2}>检验依据</CCell>
          <Cell colSpan={4}>
            TSG 11-2020《锅炉安全技术规程》、GB/T 1576—2018《工业锅炉水质》、<br/>
            NB/T 10937-2022《锅炉水（介）质处理检验导则》
          </Cell>
        </TableRow>
      </TableBody>
    </Table>
  </>;
};

const 检验结果选=['√','○','×','—'];
export const 多用的结选=['符合要求','基本符合要求','不符合要求'];
interface AttachInspectItemProps extends InternalItemProps {
  label: string;
  iAname?: string[];           //附加的存储那些字段     ，'观测备注'
  config: any[];
}
export const itemA处理系: string[] = ['水处理结' ];
// items处理系统.forEach(([name, title, initIsp], i: number) => {
//   itemA处理系.push(name as string);
// });
//【非常特殊的】   唯一性检查！
export const AttachInspectItem=
    React.forwardRef(({children, show, alone = true, refWidth, label, iAname,config}: AttachInspectItemProps, ref
    ) => {
      const {inp, setInp} = useItemInputControl({ref});
      const itemA = React.useMemo(() => {
        let itemAm: string[]=[];
        config.forEach(([name, title, initIsp], i: number) => {
          itemAm.push(name as string);
        });
        return [ ...iAname ?? [], ...itemAm, ...itemA处理系];
      }, [config, iAname]);
      const [getInpFilter] = useMeasureInpFilter(null, itemA,);
      const titNode=useOmnipotentPrefTitle({config});
      return (
          <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                               alone={alone} label={label}>
            <Text variant="h5">{label}：</Text>
            {config.map(([name, _1, _2, unit]: any, i: number) => {
              //前缀可支持三个附加列配置的；
              return (<React.Fragment key={i}>
                <div css={{display: 'flex', flexWrap: 'wrap', alignItems: 'center'}}>
                  {titNode[i]}
                  &nbsp;
                  <div>
                    检查结果
                    <InputIdProvider>
                      <InputDatalist value={(inp?.[name]?.r) || ''} datalist={检验结果选}
                                     style={{display: 'inline-flex', width: '11rem'}}
                                     onListChange={v => objNestSet(name, 'r', v || undefined, inp, setInp)}/>
                    </InputIdProvider>
                    {unit}
                  </div>
                </div>
              </React.Fragment>);
            })}
            {tail注解}
            <InputLine label={`锅炉水处理情况核查结果`}>
              <SelectInput value={ inp?.水处理结 ||''}  list={多用的结选}
                           onChange={e => setInp({ ...inp, 水处理结: e.currentTarget.value||undefined}) } />
            </InputLine>
            {children}
          </InspectRecordLayout>
    );
});

const HalfComponent: React.FC<{ rep: { modeltype: string; modelversion: string; id: string },tag:string, children: React.ReactNode }> =
    ({ rep,tag, children }) => {
  return (
      <Table fixed={["22%", "%", "18%"]} css={{ borderCollapse: 'collapse' }} tight miniw={800}>
        <TableHead>
          <TableRow>
            <CCell colSpan={2}>核查项目及其内容</CCell>
            <CCell>结果</CCell>
          </TableRow>
        </TableHead>
        <TableBody>
          <RepLink rep={rep} tag={tag}>
            {children}
          </RepLink>
        </TableBody>
      </Table>
  );
};

const tailRender=(orc: any, name: string)=><>
  <CCell>{orc?.[name]?.r??'—'}</CCell>
</>;
//续页二
export const 测试结论报告= ({ orc, rep,theme } : { orc: any, rep: any,theme:any}
) => {
  const [renderLeft,renderRight]=useOmnipotentPref({orc, config:items处理系统,
            tailRender, pcols:1, noNo:true, unitCel:false,split:[4]});
  return <>
    <div css={{"@media print": {paddingBottom: '4rem', pageBreakInside: 'avoid'}}}>
      <Text id={'ConclusionA2'} variant="h2" css={{textAlign: 'center', marginTop: '1rem',
      }}>工业锅炉水处理定期检验报告(续页二)</Text>
      <div css={{display: 'flex', justifyContent: 'space-between'}}>
        <Text></Text>
        <Text>报告编号：{rep.isp.no}</Text>
      </div>
    </div>
    <Table fixed={["22.5%","%"]} css={{borderCollapse: 'collapse', "@media print": {marginTop: '-4rem'}}} tight miniw={800}>
      <TableBody>
        <TableRow>
          <Cell split colSpan={2} css={{borderCollapse: 'collapse', height: '100%', padding: 0,}}>
            <div css={{
              display: 'flex', flexDirection: 'column',
              [theme.mediaQueries.md + ', print']: {flexDirection: 'row'},
              "@media print": {marginTop: '0rem'}
            }}>
                {/*左边不能加, height:'100%' 【打印】跨页 超过一页就重叠了，也不要height:'fill-available',左边内容高度更大的； */}
                <HalfComponent tag={'AttachInspect'} rep={rep}>
                  {renderLeft}
                </HalfComponent>
                {/*左边哪一个表不能加, 右边这个却可以加height:'100%' 【打印】  */}
                <HalfComponent tag={'AttachInspect'} rep={rep}>
                  {renderRight}
                </HalfComponent>
            </div>
          </Cell>
        </TableRow>
        <TableRow>
          <CCell>锅炉水处理情况核查结果</CCell>
          <CCell ><div css={{whiteSpace: 'pre-wrap'}}>
            {orc.水处理结 || '／'}
          </div></CCell>
        </TableRow>
        <RepLink rep={rep} tag='Conclusion'>
          <TableRow>
            <Cell colSpan={2}><div css={{minHeight: '3rem', whiteSpace: 'pre-wrap'}}>
              检验意见和建议：<br/>
              {orc.结论说明 || '／'}
            </div></Cell>
          </TableRow>
          <TableRow>
            <CCell>水处理定期检验结论</CCell>
            <CCell ><div css={{}}>
              <Text>{orc.检验结论 || '／'}，</Text>
              <Text>整改期限为：{orc.整改期限 || '／'}，</Text>
              <Text>下次检验日期 {orc.新下检日 || '／'}</Text>
            </div></CCell>
          </TableRow>
        </RepLink>
      </TableBody>
    </Table>
  </>;
};
